<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="keywords" label="关键字">
          <el-input
            v-model="queryParams.keywords"
            placeholder="客户名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item class="search-buttons">
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="hover" class="data-table">
      <div class="data-table__toolbar">
        <div class="data-table__toolbar--actions">
          <el-button type="primary" plain icon="plus" @click="handleOpenDialog()">新增</el-button>
          <el-button
            type="danger"
            :disabled="ids.length === 0"
            icon="delete"
            @click="handleDelete()"
          >
            删除
          </el-button>
        </div>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="customerList"
        highlight-current-row
        border
        class="data-table__content"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="名称" prop="name" width="150" />
        <el-table-column label="性别" width="60" align="center">
          <template #default="scope">
            <DictLabel v-model="scope.row.sex" code="gender" />
          </template>
        </el-table-column>
        <el-table-column label="电话" prop="phone" width="150" />
        <el-table-column label="邮箱" prop="email" width="150" />
        <el-table-column label="生日" prop="birthday" width="150" />
        <el-table-column label="地址" prop="address" width="150" />
        <el-table-column label="标签">
          <template #default="scope">
            <template v-if="scope.row.tags && scope.row.tags.trim()">
              <el-tag
                v-for="(tag, index) in scope.row.tags.split(',').filter((t: string) => t.trim())"
                :key="index"
                style="margin-right: 5px"
                closable
                @close="handleCloseTag(scope.row, index)"
              >
                {{ tag.trim() }}
              </el-tag>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="描述" align="center" prop="remark" />

        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              icon="position"
              @click="showAddTag(scope.row)"
            >
              添加标签
            </el-button>
            <el-button
              :disabled="scope.row.systemd"
              type="primary"
              size="small"
              link
              icon="edit"
              @click="handleOpenDialog(scope.row.id)"
            >
              编辑
            </el-button>
            <el-button
              :disabled="scope.row.systemd"
              type="danger"
              size="small"
              link
              icon="delete"
              @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="fetchData"
      />
    </el-card>

    <!-- 客户表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      @close="handleCloseDialog"
    >
      <el-form ref="roleFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入客户名称" />
        </el-form-item>

        <el-form-item label="性别" prop="sex">
          <Dict v-model="formData.sex" code="gender" />
        </el-form-item>

        <el-form-item label="生日" prop="birthday">
          <el-date-picker
            v-model="formData.birthday"
            value-format="YYYY-MM-DD"
            type="date"
            placeholder="选择生日日期"
          />
        </el-form-item>

        <el-form-item label="电话" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入电话" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱" />
        </el-form-item>

        <el-form-item label="地址" prop="address">
          <el-input v-model="formData.address" placeholder="请输入地址" />
        </el-form-item>

        <el-form-item label="描述" prop="remark">
          <el-input v-model="formData.remark" placeholder="请输入客户描述" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="tagDialogVisible" title="添加标签" width="30%">
      <el-form label-width="100px">
        <el-input
          v-model="newTag"
          placeholder="输入新标签，多个用逗号分隔"
          @keyup.enter="handleAddTag"
        ></el-input>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="tagDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddTag">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useAppStore } from "@/store/modules/app.store";
import { DeviceEnum } from "@/enums/settings/device.enum";

import CustomerAPI, {
  CustomerPageVO,
  CustomerForm,
  CustomerPageQuery,
} from "@/api/business/customer/customer.api";
defineOptions({
  name: "Customer",
  inheritAttrs: false,
});

const appStore = useAppStore();

const queryFormRef = ref();
const roleFormRef = ref();
const permTreeRef = ref();

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);
const tagDialogVisible = ref(false);
const newTag = ref("");
const queryParams = reactive<CustomerPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

let addTagCustomerVo = reactive<CustomerPageVO>({
  id: "",
  tags: "",
});

// 客户表格数据
const customerList = ref<CustomerPageVO[]>();
// 菜单权限下拉
const menuPermOptions = ref<OptionType[]>([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

const drawerSize = computed(() => (appStore.device === DeviceEnum.DESKTOP ? "600px" : "90%"));

// 客户表单
const formData = reactive<CustomerForm>({});

const rules = reactive({
  name: [{ required: true, message: "请输入客户名称", trigger: "blur" }],
  phone: [
    {
      required: true,
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  address: [{ required: true, message: "请输入客户地址", trigger: "blur" }],
  email: [
    {
      pattern: /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/,
      message: "请输入正确的邮箱地址",
      trigger: "blur",
    },
  ],
});

// 选中的客户
interface CheckedRole {
  id?: string;
  name?: string;
}
const checkedRole = ref<CheckedRole>({});
const assignPermDialogVisible = ref(false);

const permKeywords = ref("");
const isExpanded = ref(true);

const parentChildLinked = ref(true);

function showAddTag(customerVo: CustomerPageVO) {
  tagDialogVisible.value = true;
  addTagCustomerVo = { ...customerVo };
}

function handleAddTag() {
  if (addTagCustomerVo) {
    if (!addTagCustomerVo.tags) {
      addTagCustomerVo.tags = "";
    }
    // 去掉重复的
    const existingArray = addTagCustomerVo.tags
      ? addTagCustomerVo.tags.split(",").filter((t) => t.trim())
      : [];
    const newArray = newTag.value.split(",").filter((t) => t.trim());
    const uniqueTags = [...new Set([...existingArray, ...newArray])];
    const newTags = uniqueTags.join(",");
    CustomerAPI.updateTag(addTagCustomerVo.id, uniqueTags).finally(() => {
      tagDialogVisible.value = false;
      customerList.value?.forEach((e) => {
        if (e.id == addTagCustomerVo.id) {
          e.tags = newTags;
        }
      });
    });
  }
}

function handleCloseTag(customerVo: CustomerPageVO, tagIndex: number) {
  if (customerVo.tags) {
    // 将字符串转为数组
    const tagsArray = customerVo.tags.split(",");
    // 移除指定索引的标签
    tagsArray.splice(tagIndex, 1);
    // 更新数据（这里假设row是响应式的）
    customerVo.tags = tagsArray.join(",");
    CustomerAPI.updateTag(customerVo.id, tagsArray);
  }
}

// 获取数据
function fetchData() {
  loading.value = true;
  CustomerAPI.getPage(queryParams)
    .then((data) => {
      customerList.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 查询（重置页码后获取数据）
function handleQuery() {
  queryParams.pageNum = 1;
  fetchData();
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  fetchData();
}

// 行复选框选中
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

// 打开客户弹窗
function handleOpenDialog(roleId?: string) {
  dialog.visible = true;
  if (roleId) {
    dialog.title = "修改客户";
    CustomerAPI.getFormData(roleId).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增客户";
  }
}

// 提交客户表单
function handleSubmit() {
  roleFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const roleId = formData.id;
      if (roleId) {
        CustomerAPI.update(roleId, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        CustomerAPI.create(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;

  roleFormRef.value.resetFields();
  roleFormRef.value.clearValidate();

  formData.id = undefined;
  formData.remark = "";
}

// 删除客户
function handleDelete(roleId?: number) {
  const roleIds = [roleId || ids.value].join(",");
  if (!roleIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    loading.value = true;
    CustomerAPI.deleteByIds(roleIds)
      .then(() => {
        ElMessage.success("删除成功");
        handleResetQuery();
      })
      .finally(() => (loading.value = false));
  });
}

// 权限筛选
watch(permKeywords, (val) => {
  permTreeRef.value!.filter(val);
});

onMounted(() => {
  handleQuery();
});
</script>
